require('page/common/header/index.js')
var _catalog_service = require('service/catalog-service.js');
var _cart_service = require('service/cart-service.js');
var listTemplate = require('./index.string')
const _util = require('../../../util/util');

var category = {
  listData: {
    title: '',
    headList: [],
    productList: [],
    itemList: []
  },
  productHeadList: [
    'Product ID',
    'Name'
  ],
  itemHeadList: [
    'Item ID',
    'Product ID',
    'Description',
    'List Price',
    ' '
  ],

  init : function(){
    this.loadProductInfo();
    this.bindEvents();
    return this;
  },

  //向服务器发送请求，获取该categoryId下的products
  loadProductInfo: function(){
    var route = _util.getURLParam('route');

    if(route === 'product'){
      var categoryId = _util.getURLParam('categoryId');
      $('#BackLink').html(
        `<a href="./catalog-main.html">Return to Main Menu</a>`
      )
      _catalog_service.getProductsByCategoryId(
        categoryId,
        res => {
          let productList = res.data;
          this.listData.headList = this.productHeadList;
          this.listData.title = categoryId;
          this.listData.productList = productList;
          this.listData.itemList = null;

          var result = _util.renderHtml(listTemplate, {ListData: this.listData});
          $('#Catalog').html(result);
        }, 
        errMsg => {
          
        }
      )
    }
    else if(route === 'item'){
      var productId = _util.getURLParam('productId');
      _catalog_service.getItemsByProductId(
        productId,
        res => {
          let itemList = res.data;
          $('#BackLink').html(
            `<a href="./catalog-list.html?categoryId=${itemList[0].categoryId}&route=product">Return to ${itemList[0].categoryId}</a>`
          )
          this.listData.headList = this.itemHeadList;
          this.listData.title = productId;
          this.listData.productList = null;
          this.listData.itemList = itemList;

          var result = _util.renderHtml(listTemplate, {ListData: this.listData});
          $('#Catalog').html(result);

          this.bindAddToCart();
        }, 
        errMsg => {
          
        }
      )
    }

    
  },

  //绑定事件
  bindEvents: function(){
    
  },

  //为Add to Cart按钮绑定单击事件
  bindAddToCart: function() {
    $('.Button').each(function () {
        $(this).on('click',function () {
          
          console.log('我被点击了！');
          const itemId = $(this).attr('id');
          console.log(itemId);

          //发送ajax请求，向购物车中添加该商品
          _cart_service.add_cart(
            itemId,
            //商品已添加到购物车，进行页面跳转
            function(res){
              window.location.href = '../../view/cart/cart.html?redirect='+encodeURIComponent(window.location.href);
            },
            function(errMsg){
              
            }
          )
        });
    });
  }
};

module.exports = category.init();